package com.secneo.appshare.activities;

import java.io.ByteArrayOutputStream;
import java.util.List;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.secneo.appshare.AppShareApplication;
import com.secneo.appshare.R;
import com.secneo.appshare.adapter.FeedsAdapter;
import com.secneo.appshare.adapter.RecomAdapter;
import com.secneo.appshare.api.LocalStore;
import com.secneo.appshare.api.RemoteApi.AppRecom;
import com.secneo.appshare.api.RemoteApi.Feed;
import com.secneo.appshare.api.RemoteApi.Feeds;
import com.secneo.appshare.common.Constants;
import com.secneo.appshare.threads.FeedsThread;
import com.secneo.appshare.threads.RecomThread;

public class SearchResultActivity extends CommonMenuActivity implements OnClickListener
{

	private String uid;
	private ProgressBar progress_user_apps;
	private GridView mAppGridView;
	private GridView mUserGridView;
	private RecomAdapter mSAppAdapter;
	private FeedsAdapter mSUserAdapter;
	private RadioButton buttonApp;
	private RadioButton buttonUser;
	private TextView textNoResult;

	public static final int MSG_GET_OTHER_USER_ICON = 101;
	Drawable dw =null;
    String appIconUrl="";
    
    String userKeyword = "";
    String appKeyword = "";
	private EditText mKeywordEditText;
    
	boolean mSearchingApp = false;
	boolean mSearchingUser = false;

	private RecomThread mRecomThread = null;
	private FeedsThread mFeedsThread = null;
	

	private Handler mRecomAppHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch(msg.what) {
				
			case Constants.MSG_GET_FEEDS_NETWORK_ERROR:
				mSearchingUser = false;
				break;
			case Constants.MSG_GET_RECOMS_NETWORK_ERROR:
				mSearchingApp = false;
				break;
			case Constants.MSG_GET_RECOMS_FINISH:
				buttonApp.setClickable(true);
				buttonUser.setClickable(true);
				mSearchingApp = false;
				refreshAppGridView(mRecomThread.getAppList());
				break;
			case Constants.MSG_GET_FEEDS_FINISH:
				buttonApp.setClickable(true);
				buttonUser.setClickable(true);
				mSearchingUser = false;
				refreshUserGridView(mFeedsThread.getFeeds());
				break;
			case Constants.MSG_GET_APPICON_FINISH:
				mAppGridView.invalidateViews();
				break;
			case Constants.MSG_GET_FEEDICON_FINISH:
				mUserGridView.invalidateViews();
				break;
			}
			super.handleMessage(msg);
		}
	};
	

	
	class RecomAppGridViewItemClickListener implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
		{
			try  {
				// Start application activity
				 Intent intent = new Intent(); 
				 intent.setClass(SearchResultActivity.this, ApplicationActivity.class);
				 List<AppRecom> mList = SearchResultActivity.this.mRecomThread.getAppList();
				 AppRecom app_recom = mList.get(position);
				 Bundle mBundle = new Bundle(); 
				 mBundle.putString("package_name", app_recom.package_name);
				 mBundle.putInt("n", 20);
				 String uid = LocalStore.getLocaleStoreInstance(SearchResultActivity.this).getUid();
				 mBundle.putString("uid", uid);
				 mBundle.putBoolean("installed_not_addicted", true);
				 
				PackageManager manager = SearchResultActivity.this.getPackageManager();
				try 
				{
					PackageInfo info = manager.getPackageInfo(app_recom.package_name, 0);
					if (info != null)
						mBundle.putBoolean("user_app_flag", true);
					else
						mBundle.putBoolean("user_app_flag", false);
				
				} catch (Exception e) {
					mBundle.putBoolean("user_app_flag", false);
				}
				 
				 /* Send the icon */
				 mBundle.putString("app_icon", app_recom.app_icon);
				if (app_recom.app_icon_drawable != null) {
					try {
						Bitmap bitmap = ((BitmapDrawable) app_recom.app_icon_drawable)
								.getBitmap();
						ByteArrayOutputStream stream = new ByteArrayOutputStream();

						bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
						byte[] bitmapdata = stream.toByteArray();
						mBundle.putByteArray("app_icon_array", bitmapdata);
					} catch (Exception ex) {
						ex.printStackTrace();
						mBundle.putByteArray("app_icon_array", null);
					}

				} else {
					mBundle.putByteArray("app_icon_array", null);
				}
				mBundle.putString("app_name", app_recom.app_name);
			
				 
				 intent.putExtras(mBundle);
				 startActivity(intent);
			} catch(Exception ex) {
				ex.printStackTrace();
			}
			return;
			
		} 
		
	}
	
	class FeedsGridViewItemClickListener implements OnItemClickListener 
	{
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
		{
			try 
			{
				Intent intent = new Intent();
				intent.setClass(SearchResultActivity.this, AppsOtherUserActivity.class);

				Bundle mBundle = new Bundle();
				String uid = LocalStore.getLocaleStoreInstance(SearchResultActivity.this).getUid();
				mBundle.putString("uid", uid);

				Feeds feeds;
				feeds = mFeedsThread.getFeeds();

				List<Feed> feedsList = feeds.feeds;
				Feed feed = feedsList.get(position);
				mBundle.putString("other_uid", feed.uid);
				mBundle.putString("user_icon", feed.user_icon);
				mBundle.putString("user_name", feed.user_name);
				
				intent.putExtras(mBundle);
				startActivity(intent);
				
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	}
    
    

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.appshare_search_result);
		AppShareApplication.getInstance().addActivity(this);
		Bundle bundle = getIntent().getExtras();
		appKeyword = bundle.getString("keyword");

		mKeywordEditText = (EditText) findViewById(R.id.text_account);
		mKeywordEditText.setText(appKeyword);
		mSearchingApp = false;
		mSearchingUser = false;
		
		progress_user_apps = (ProgressBar) findViewById(R.id.progress_user_apps);
		mAppGridView = (GridView) findViewById(R.id.grid_search_apps);
		mAppGridView.setOnItemClickListener(new RecomAppGridViewItemClickListener());
		mUserGridView = (GridView) findViewById(R.id.grid_search_users);
		mUserGridView.setOnItemClickListener(new FeedsGridViewItemClickListener());
		
		textNoResult = (TextView) findViewById(R.id.no_result_text);

		buttonApp = (RadioButton) findViewById(R.id.toggle_app);
		buttonApp.setOnClickListener(this);
		buttonApp.setChecked(true);

		buttonUser = (RadioButton) findViewById(R.id.toggle_user);
		buttonUser.setOnClickListener(this);
		
		Button returnButton=(Button)findViewById(R.id.img_ret);
		returnButton.setOnClickListener(new OnClickListener() 
		{
			@Override
			public void onClick(View v) {
				finish();
			}
		});

		TextView searchButton=(TextView)findViewById(R.id.img_search);
		searchButton.setOnClickListener(new OnClickListener() 
		{
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String keyword = mKeywordEditText.getText().toString();
				if("".equalsIgnoreCase(keyword)){
					return;
				}
				if(buttonApp.isChecked())
				{
					appKeyword = keyword;
					startAppsThread();
					return;
				}
				else if(buttonUser.isChecked())
				{
					userKeyword = keyword;
					startFeedsThread();
					return;
				}
			}
		});

		startAppsThread();
	}
	

	@Override
	public void onClick(View v) 
	{
		if (v instanceof RadioButton) 
		{
			if(buttonApp.isChecked())
			{
				if(mRecomThread==null)
				{
					startAppsThread();
				}
				else
				{
					refreshAppGridView(mRecomThread.getAppList());
				}
				return;
			}
			if(buttonUser.isChecked())
			{
				if(mFeedsThread==null)
				{
					startFeedsThread();
				}
				else
				{
					refreshUserGridView(mFeedsThread.getFeeds());
				}
				return;
			}
		}
	}
	
	
	public void refreshAppGridView(List<AppRecom> list) {

		int listCount = list.size();
		progress_user_apps.setVisibility(View.GONE);
		mUserGridView.setVisibility(View.GONE);
		if(listCount>0)
		{
			mAppGridView.setAdapter(null);
			if(mSAppAdapter != null)
			{
				mSAppAdapter.freeDrawable();
				mSAppAdapter = null;
			}
			mSAppAdapter = new RecomAdapter(this, list);
			textNoResult.setVisibility(View.GONE);
			mAppGridView.setVisibility(View.VISIBLE);
			mAppGridView.setNumColumns(4);
			mAppGridView.setAdapter(mSAppAdapter);
		}
		else{
			textNoResult.setVisibility(View.VISIBLE);
		}
		
	}
	
	@Override
	protected void onDestroy()
	{
		mAppGridView.setAdapter(null);
		if(mSAppAdapter != null)
		{
			mSAppAdapter.freeDrawable();
			mSAppAdapter = null;
		}
		mUserGridView.setAdapter(null);
		if(mSUserAdapter != null)
		{
			mSUserAdapter.freeDrawable();
			mSUserAdapter = null;
		}
		super.onDestroy();
	}

	public void refreshUserGridView(Feeds feeds) {

		int listCount = feeds.feeds.size();
		progress_user_apps.setVisibility(View.GONE);
		mAppGridView.setVisibility(View.GONE);
		if(listCount>0)
		{
			mUserGridView.setAdapter(null);
			if(mSUserAdapter != null)
			{
				mSUserAdapter.freeDrawable();
				mSUserAdapter = null;
			}
			mSUserAdapter = new FeedsAdapter(this, feeds.feeds);
			textNoResult.setVisibility(View.GONE);
			mUserGridView.setVisibility(View.VISIBLE);
			mUserGridView.setNumColumns(4);
			mUserGridView.setAdapter(mSUserAdapter);
		}
		else{
			textNoResult.setVisibility(View.VISIBLE);
		}
	}
	

	private void startFeedsThread() 
	{
		if("".equalsIgnoreCase(userKeyword)){
			progress_user_apps.setVisibility(View.GONE);
			mAppGridView.setVisibility(View.GONE);
			mUserGridView.setVisibility(View.GONE);
			textNoResult.setVisibility(View.GONE);
			return;
		}
		
		if(true == mSearchingUser){
			Log.e("search", "user searching return");
			return;
		}
		mSearchingUser = true;
		
		progress_user_apps.setVisibility(View.VISIBLE);
		mAppGridView.setVisibility(View.GONE);
		mUserGridView.setVisibility(View.GONE);
		textNoResult.setVisibility(View.GONE);
		
		buttonApp.setClickable(false);
		buttonUser.setClickable(false);

		mFeedsThread = new FeedsThread(this, mRecomAppHandler, 0, userKeyword, Constants.USER_TYPE_SEARCH, Constants.feedGetTypeAll);
		mFeedsThread.start();
	}

	private void startAppsThread() 
	{		
		if("".equalsIgnoreCase(appKeyword)){
			progress_user_apps.setVisibility(View.GONE);
			mAppGridView.setVisibility(View.GONE);
			mUserGridView.setVisibility(View.GONE);
			textNoResult.setVisibility(View.GONE);
			return;
		}
		
		if(true == mSearchingApp){
			Log.e("search", "app searching return");
			return;
		}
		mSearchingApp = true;
		
		progress_user_apps.setVisibility(View.VISIBLE);
		mAppGridView.setVisibility(View.GONE);
		mUserGridView.setVisibility(View.GONE);
		textNoResult.setVisibility(View.GONE);
		
		buttonApp.setClickable(false);
		buttonUser.setClickable(false);

		mRecomThread = new RecomThread(this, mRecomAppHandler, Constants.APP_TYPE_SEARCH, appKeyword, 0,-1000);
		mRecomThread.start();
	}
	
}
